package org.huawei.dao;

import org.huawei.utils.DatabaseUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class RoleDao {
    public List<String> getAllRoleNames() throws SQLException {
        List<String> roleNames = new ArrayList<>();
        String query = "SELECT roleName FROM role";

        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            // 遍历结果集
            while (rs.next()) {
                String roleName = rs.getString("roleName");
                roleNames.add(roleName);
            }
        }
        return roleNames;
    }

    // 根据角色名称获取对应的RoleId
    public int getRoleIdByRoleName(String roleName) {
        // 从数据库中查找角色名称对应的RoleId
        String query = "SELECT roleId FROM role WHERE roleName = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, roleName);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt("roleId");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;  // 如果找不到对应的角色名，返回-1表示错误
    }

    // 根据RoleId获取对应的RoleName
    public String getRoleNameByRoleId(int roleId) {
        String query = "SELECT roleName FROM role WHERE roleId = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, roleId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getString("roleName");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;  // 如果找不到对应的角色ID，返回null
    }
}
